//
//  PhotoBrowserCell.swift
//  PhotoBrowser
//
//  Created by haoran on 16/4/28.
//  Copyright © 2016年 xuhaoran. All rights reserved.
//

import UIKit
import SDWebImage
class PhotoBrowserCell: UICollectionViewCell {

    // MARK:- 懒加载
    lazy var imageView : UIImageView = UIImageView()
    
    // MARK:- 定义的属性
    var shop : Shop? {
        didSet{
            // 1.nil值校验
            guard let urlString = shop?.q_pic_url else {
                return
            }
            
            // 2.获取小图
            var smallImage = SDWebImageManager.sharedManager().imageCache.imageFromMemoryCacheForKey(urlString)
            if smallImage == nil {
                smallImage = UIImage(named: "empty_picture")
            }
            
            // 3.计算frame
            imageView.frame = calculateFrame(smallImage)
            
            // 4.设置大图
            guard let bigURLString = shop?.z_pic_url else {
               return
            }
            
            let url = NSURL(string: bigURLString)
            imageView .sd_setImageWithURL(url, placeholderImage: smallImage, options: .RetryFailed) { (image, error, type, url) -> Void in
                
                // 需要重新设置frame,不然图片就会被拉伸导致比例不正确
                self.imageView.frame = self.calculateFrame(image)
            }
        }
    
    }
    
    // MARK:- 构造函数
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
}


// MARK:- 根据图片计算最终的frame
extension PhotoBrowserCell {

  func calculateFrame(image : UIImage) -> CGRect {
        let x : CGFloat = 0
        let width = UIScreen.mainScreen().bounds.width
        let height = width / image.size.width * image.size.height
        let y = (UIScreen.mainScreen().bounds.height - height) * 0.5
        
        return CGRect(x: x, y: y, width: width, height: height)
        
    }

}

// MARK:- 设置UI
extension PhotoBrowserCell {
    func setupUI() {
        // 1.添加子控件
        contentView.addSubview(imageView)
    }


}
